<template>
  <div class="space-y-4">
    <!-- 动态渲染面板 -->
    <component
      v-for="panel in visiblePanels"
      :key="panel.id"
      :is="panelComponents[panel.id]"
      :panel="panel"
      :conversation-type="conversationType"
      @panel-click="handlePanelClick"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, watch, markRaw } from 'vue'
import type { ResultPanel } from '../../types/home'
import { getPanelComponentName } from '../../utils/panelComponents'

// 静态导入所有面板组件
const panelModules = import.meta.glob('./*.vue', { eager: true })

interface Props {
  panels: ResultPanel[]
  conversationType: string
}

interface Emits {
  (e: 'panel-click', panel: ResultPanel): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 组件缓存
const panelComponents = ref<Record<number, any>>({})

// 只显示可见的面板
const visiblePanels = computed(() => {
  return props.panels.filter(panel => panel.visible)
})

// 加载面板组件
const loadPanelComponents = () => {
  for (const panel of props.panels) {
    if (!panelComponents.value[panel.id]) {
      try {
        const componentName = getPanelComponentName(panel.id, props.conversationType)
        const componentPath = `./${componentName}.vue`
        
        if (panelModules[componentPath]) {
          panelComponents.value[panel.id] = markRaw(panelModules[componentPath].default)
        } else {
          console.warn(`Panel component ${componentName} not found, using default`)
          // 使用DefaultPanel作为默认组件
          if (panelModules['./DefaultPanel.vue']) {
            panelComponents.value[panel.id] = markRaw(panelModules['./DefaultPanel.vue'].default)
          } else {
            // 创建一个简单的默认组件
            panelComponents.value[panel.id] = markRaw({
              template: '<div class="bg-white border border-slate-200 rounded-lg p-4">Default Panel</div>'
            })
          }
        }
      } catch (error) {
        console.error(`Failed to load panel component for panel ${panel.id}:`, error)
        // 确保始终有一个默认组件
        panelComponents.value[panel.id] = markRaw({
          template: '<div class="bg-white border border-slate-200 rounded-lg p-4">Error Loading Panel</div>'
        })
      }
    }
  }
}

// 处理面板点击
const handlePanelClick = (panel: ResultPanel) => {
  emit('panel-click', panel)
}

// 监听面板变化，重新加载组件
watch(() => props.panels, loadPanelComponents, { immediate: true, deep: true })
</script>

<style scoped>
.space-y-4 > * + * {
  margin-top: 1rem;
}
</style>